#include <vector>
#include <stack>
#include <string>

using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

class Solution {
public:

    //根据二叉树创建字符串
    string tree2str(TreeNode* root) {
        if (root == nullptr)
            return "";
        if (root->left==nullptr && root->right==nullptr)
        {
            return to_string(root->val);
        }
        if (root->right == nullptr)
        {
            return to_string(root->val) + '(' + tree2str(root->left) + ')';
        }
        return to_string(root->val) + '(' + tree2str(root->left) + ")(" + tree2str(root->right) + ')';
    }

    //前序遍历迭代版
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> ans;
        stack<TreeNode*> st;
        TreeNode* cur = root;
        while (cur || !st.empty())
        {
            while (cur)
            {
                ans.push_back(cur->val);
                st.push(cur);
                cur = cur->left;
            }
            cur = (st.top())->right;
            st.pop();
        }
        return ans;
    }

    //后续遍历迭代版
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> ans;
        stack<TreeNode*> st;
        TreeNode* cur = root;
        TreeNode* prev = nullptr;
        while (cur!=nullptr || !st.empty())
        {
            while (cur != nullptr)
            {
                st.push(cur);
                cur = cur->left;
            }

            TreeNode* top = st.top();
            if (top->right == nullptr || top->right == prev)
            {
                ans.push_back(top->val);
                prev = top;
                st.pop();
            }
            else 
            {
                cur = top->right;
            }
        }
        return ans;
    }

    //从前序与中序遍历序列构造二叉树
    TreeNode* _buildTree(vector<int>& preorder, vector<int>& inorder, int& prei, int inbegin, int inend) 
    {
        if (inbegin > inend)
            return nullptr;
        
        //找root
        int root = inbegin;
        while (root <= inend)
        {
            if (inorder[root] == preorder[prei])
                break;
            else
                ++root;
        }
        TreeNode* node = new TreeNode(preorder[prei++]);

        node->left = _buildTree(preorder, inorder, prei, inbegin, root-1);
        node->right = _buildTree(preorder, inorder, prei, root+1, inend);

        return node;
    }

    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int prei = 0;
        return _buildTree(preorder, inorder, prei, 0, inorder.size()-1);
    }
};